#include<iostream>
#include<algorithm>
using namespace std;
int n;
int a[10001];
int Count()
{
	int f[100];
	f[0] = 1;
	for (int i = 1; i < 26; i++)
	{
		f[i] = f[i-1]*i;
	}
	if (n == 1) return 0;
	else
	{
		int count = 0;
		for (int i = 0; i < n; i++)
		{
			int t=0;
			for (int j = 0; j < i; j++)
			{
				if (a[j] < a[i]) t++;
			}
			count += (a[i]-1-t)*f[n-i-1];
		}
		return count;
	} 
}
int main()
{
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		cin >> a[i];
	}
	cout << Count() << endl;
	next_permutation(a, a+n);
	for (int i = 0; i < n; i++)
	{
		cout << a[i] << " ";
	}
	cout << endl;
}
